package com.hzit.item.service.impl;

import com.alibaba.fastjson2.JSON;
import com.hzit.item.service.ItemService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.RemoteManagerService;
import com.ruoyi.system.api.domain.Goods;
import com.ruoyi.system.api.domain.GoodsDesc;
import com.ruoyi.system.api.domain.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.context.IContext;

import javax.xml.crypto.Data;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class ItemServiceImpl implements ItemService {
	//1. 引入模板引擎
	@Autowired
	private TemplateEngine engine;
	@Autowired
	private RemoteManagerService managerService;

	//2. 生成静态页面
	@Override
	public void createPage(Long id) throws IOException {
		//2.1 定义出模板引擎工作的上下文环境,主要用于绑定数据
		Context context = new Context();
		//第一步：查询goods商品对象（spu）
		//2.1.1 根据商品id查询商品对象
		R<Goods> goodsR = managerService.findGoodsById(id);
		Goods goods = goodsR.getData();
		//2.1.2 将spu商品放到context中
		Map<String, Object> data = new HashMap<>();
		data.put("goods",goods);

		//第二步：查询goodsDesc商品描述对象
		R<GoodsDesc> goodsDescR = managerService.findDescById(id);
		GoodsDesc goodsDesc = goodsDescR.getData();
		data.put("goodsDesc",goodsDesc);
		String specificationItemsInfo = goodsDesc.getSpecificationItems();
		String customAttributeItemsInfo = goodsDesc.getCustomAttributeItems();
		String itemImagesInfo = goodsDesc.getItemImages();
		//将上面的三种字符串转换为List<Map>对象
		List<Map> specificationItems = JSON.parseArray(specificationItemsInfo, Map.class);
		List<Map> customAttributeItems = JSON.parseArray(customAttributeItemsInfo, Map.class);
		List<Map> itemImages = JSON.parseArray(itemImagesInfo, Map.class);
		data.put("specificationItems",specificationItems);
		data.put("customAttributeItems",customAttributeItems);
		data.put("itemImages",itemImages);

		// 第三步：根据分类id查询出分类名字
		R<String> name1R = managerService.findNameById(goods.getCategory1Id());
		String cateName1 = name1R.getData();
		R<String> name2R = managerService.findNameById(goods.getCategory2Id());
		String cateName2 = name2R.getData();
		R<String> name3R = managerService.findNameById(goods.getCategory3Id());
		String cateName3 = name3R.getData();
		data.put("name1",cateName1);
		data.put("name2",cateName2);
		data.put("name3",cateName3);

		//第三步：根据spu商品id查询sku商品列表
		R<List<Item>> listR = managerService.findItemsByGoodsId(id);
		List<Item> itemList = listR.getData();
		data.put("itemList",itemList);

		context.setVariables(data);
		//2.2 构造输出流，用于指定生成的文件放在哪里
		Writer writer = new FileWriter("D:\\nginx-1.24.0\\html\\item\\" + id + ".html");
		//2.3 执行模板引擎
		engine.process("item",context,writer);
	}
}
